package com.zhongyouyun.admin.controller;


import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.ObjectUtil;
import com.zhongyouyun.admin.model.DeptModel;
import com.zhongyouyun.admin.model.UserModel;
import com.zhongyouyun.other.model.Result;
import com.zhongyouyun.utils.ModelUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.zhongyouyun.admin.service.DeptService;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


/**
 * @Author: shenyi
 * @Date: 2021-12-17
 * @Description:
 */
@RestController
@RequestMapping("/admin/z_dept")
@Api(value = "部门管理controller", tags = {"部门管理接口"})
public class DeptController {
    @Autowired
    private DeptService service;

    @PostMapping("/findDeptTree")
    @ResponseBody
    @ApiOperation(value = "获取用户角色菜单", notes = "通过用户信息获取用户角色权限")
    public Result findDeptTree(@RequestBody DeptModel deptModel) {
        List<Tree<Long>> list = service.findDeptTree(deptModel);
        if (list.size() > 0) {
            Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
            resultMap.put("list", list);
            return Result.builder().message("成功").status(0).data(resultMap).build();
        } else {
            return Result.builder().message("没有任何权限").status(1).build();
        }
    }

    @PostMapping("/saveOrUpate")
    @ResponseBody
    @ApiOperation(value = "修改或者新增", notes = "通过ID判断修改或者新增")
    public Result saveOrUpate(@RequestBody DeptModel deptModel) {
        UserModel model = (UserModel) SecurityUtils.getSubject().getPrincipal(); // 获取当前登录用户
        if (ObjectUtil.isNotEmpty(model.getId()) && deptModel.getId() != 0) {
            deptModel.setUpdateBy(deptModel.getId().toString());
        } else {
            ModelUtils modelutils = new ModelUtils();
            modelutils.initModel(deptModel, model.getId().toString());
        }
        Boolean flag = service.saveOrUpdate(deptModel);
        if (flag) {
            return Result.builder().message("成功").status(0).build();
        } else {
            return Result.builder().message("成功").status(1).build();
        }
    }

    @PostMapping("/batchDelete")
    @ResponseBody
    @ApiOperation(value = "删除", notes = "通过ID删除")
    public Result batchDelete(@RequestBody List<DeptModel> userModelList) {

        List<Long> list = new ArrayList<Long>();
        userModelList.forEach(userModel -> {
            list.add(userModel.getId());
        });
        Boolean flag = service.removeByIds(list);
        if (flag) {
            return Result.builder().message("成功").status(0).build();
        } else {
            return Result.builder().message("成功").status(1).build();
        }
    }

}
